package cn.iocoder.yudao.module.promotion.groupon.service.app;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.interest.service.AppInterestBaseService;
import cn.iocoder.yudao.framework.common.exception.KnownServiceException;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.promotion.groupon.dao.GrouponPackageFavoriteMapper;
import cn.iocoder.yudao.module.promotion.groupon.pojo.po.GrouponPackageFavorite;
import cn.iocoder.yudao.module.promotion.groupon.pojo.vo.AppGrouponPackageFavoriteVO;
import cn.iocoder.yudao.module.promotion.groupon.pojo.vo.AppGrouponPackageVO;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.constant.ErrorCodeConstants.DATA_NOT_EXISTS;

/**
 * 团购套餐收藏 Service 实现类
 *
 * @author 山野羡民
 */
@Service
@Validated
public class AppGrouponPackageFavoriteServiceImpl extends AppInterestBaseService<AppGrouponPackageVO, GrouponPackageFavorite, AppGrouponPackageFavoriteVO> implements AppGrouponPackageFavoriteService {
    @Resource
    private GrouponPackageFavoriteMapper grouponPackageFavoriteMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private AppGrouponPackageService appGrouponPackageService;

    @Override
    protected GrouponPackageFavoriteMapper getInjectedMapper() {
        return grouponPackageFavoriteMapper;
    }

    @Override
    public AppGrouponPackageVO validateSnapshotExists(Long bizId) {
        AppGrouponPackageVO respVO = appGrouponPackageService.getDetail(bizId);
        if (respVO == null) {
            throw new KnownServiceException(DATA_NOT_EXISTS.getCode(), "团购套餐不存在");
        }
        return BeanUtils.toBean(respVO, AppGrouponPackageVO.class);
    }

    @Override
    public PageResult<AppGrouponPackageFavoriteVO> getPage(Integer current, Integer size, Long userId) {
        CoreQueryWrapper<GrouponPackageFavorite> wrapper = new CoreQueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("recycled", false);
        PageResult<GrouponPackageFavorite> page = grouponPackageFavoriteMapper.selectPage(current, size, wrapper);
        if (CollUtil.isEmpty(page.getList())) {
            return PageResult.empty();
        }
        return new PageResult<>(page.getList().stream().map(this::convertToViewObject).toList(), page.getTotal());
    }

}
